<template>
  <div class="page-content">
    <div class="active_product">
      <!-- 这部分是选择排序筛选 -->
      <sort_product class="flex-item" @update:selectedOption="getSelectedOption" style="margin-left: 10%;" />
      <!-- 这部分是价格区间筛选 -->
      <price_product class="flex-item" @update:price="getPrice" />
      <!-- 这部分是搜索 -->
      <search style="width: 2%; margin-right: 0%;margin-left:475px;"></search>
      <el-input v-model="input" class="search" placeholder="请输入要查找的商品"></el-input>
    </div>
    <ul v-infinite-scroll="loadMoreImages" class="infinite-list">
      <li v-for="(imageUrlsChunk, id) in chunkedImageUrls" :key="id" class="infinite-list-item">
        <div v-for="(imageUrl, subIndex) in imageUrlsChunk" :key="subIndex" class="image-container">
          <el-image :src="Path.imgPath + imageUrl.imgs" fit="fill" alt="Image" lazy class="productImg" @click="showDialog(imageUrl)">
          </el-image>
          <div>
            <div style="display: flex; justify-content: center; color: #333333; height: 40px; padding: 5%;">
              <el-text style="text-align: center;">{{ imageUrl.name }}</el-text>
            </div>
            <div style="display: flex;">
              <div style="width: 85px;margin-left: 5px; display: flex;">
                <div>
                  <view_img style="width: 20px; height: 20px;"></view_img>
                </div>
                 <div>
                    <el-text style="padding-bottom: 10px; width: 20px;">{{ imageUrl.browse }}</el-text>
                 </div>
                  
              </div>
              <div>
                <el-text style="font-size: large; color: red;">{{ imageUrl.price }}元</el-text>
              </div>
              
              <div v-if="imageUrl.store===0" style="position: absolute;margin-top: -280px;" @click="showDialog(imageUrl)">
                  <sole_out style="width: 230px;height: 230px;"></sole_out>
              </div>
            </div>
          </div>
        </div>
      </li>
    </ul>
    <el-dialog v-model="dialogVisible" style="height: 700px; width: 1200px;" :close-on-click-modal="false" :before-close="handleClose">
      <productDialog
        v-model:dialogVisible="dialogVisible"
        :selectedImage="selectedImage"
        :address="address"
        @getAddress="getAddress"
        @getGoods="getGoods"
        :before-close="handleClose"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch, onMounted } from 'vue';
import { get,post } from "@/plugins/axios"
import { Path } from "@/constant/index"
import router from '@/router';
import productDialog from "@/components/form-wjq/goodsDialog.vue"
import price_product from "@/views/store-grc/components/price_product.vue"
import sort_product from "@/views/store-grc/components/sort_product.vue"
import search from '@/components/storeByGrc/search.vue'
import sole_out from '../../../../public/images/shop-grc/sole_out.vue';
import view_img from '../../../../public/images/shop-grc/view.vue';
// 搜索输入框中绑定的数据
const input = ref('')
import { useRoute } from 'vue-router';
import VueCookie from 'vue-cookies';
const allImages = ref([]);
const filteredImages = ref([]);
const address = ref([])
const dialogVisible = ref(false);
const selectedImage = ref(null);
const route = useRoute()
const goodsID = ref(route.query.goodsID)
const categoryId = ref(route.query.categoryId)
const ifSortByPrice = ref(false)
const selectedOption =ref()
const sortPrice = ref({
  minPrice: '',
  maxPrice: ''
})

 function getGoods() {
    get(Path.goodsList, null, content => {
    allImages.value = content;
    applyFilters();
    if(goodsID.value){
      locatedAndOpenDialog()
    }
  })
 }

 getAddress()
function getAddress() {
  get(Path.addressList, null, content => {
    address.value = content
  })
}

const loadedIndex = ref(0);

const chunkedImageUrls = computed(() => {
  const chunks = [];
  for (let i = 0; i < filteredImages.value.length; i += 4) {
    chunks.push(filteredImages.value.slice(i, i + 4));
  }
  return chunks;
});

const loadMoreImages = () => {
  if (loadedIndex.value < filteredImages.value.length) {
    const chunkSize = 4;
    const endIndex = Math.min(loadedIndex.value + chunkSize, filteredImages.value.length);
    loadedIndex.value += chunkSize;
  }
};

const showDialog = (image) => {
  selectedImage.value = image;
  dialogVisible.value = true;
  post(Path.goodsIncreaseBrowse,{id:image.id},content => {})
};

const locatedAndOpenDialog = () => {
  if (goodsID.value) {
    const goods = filteredImages.value.find(p => p.id == parseInt(goodsID.value))

    if (goods) {
      showDialog(goods)
    }
  }
}
 
const getSelectedOption=(newOption)=>{
    selectedOption.value=newOption
    applyFilters()
}

const getPrice = (newPrice) => {
  sortPrice.value.minPrice = newPrice.min;
  sortPrice.value.maxPrice=newPrice.max;
  ifSortByPrice.value = true;
  applyFilters();
}
           //过滤
const applyFilters = () => {
  
  filteredImages.value = allImages.value.filter(goods => {
    const price = goods.price;
    const matchOption = ref(true)
    if(sortPrice.value.minPrice===''){
      sortPrice.value.minPrice='0';
    }
    if(sortPrice.value.maxPrice===''){
      sortPrice.value.maxPrice='10000000000';
    }
    const currentDate = new Date()
    const oneMonthAgo = new Date(currentDate.setMonth(currentDate.getMonth()-1))
    switch(selectedOption.value){
      case'当前所有':
      matchOption.value=true
      break;
      case '热门产品':
        matchOption.value = goods.sales >=100;
        break;
      case '新品上市':
        matchOption.value= new Date(goods.creatTime.replace(' ','T'))>=oneMonthAgo;
        console.dir(matchOption.value)
        break;
    }

    const matchesPrice = price >= +(sortPrice.value.minPrice===''?'0':sortPrice.value.minPrice) && price <= +(sortPrice.value.maxPrice==='0'?'1000000000':sortPrice.value.maxPrice);
    const matchesName = !input.value || goods.name.toLowerCase().includes(input.value.toLowerCase());
    const matchCategory = !categoryId.value || goods.categoryId ==categoryId.value
  
    return  matchCategory && matchesPrice && matchesName && matchOption.value  ;
  });
  switch(selectedOption.value){
    case '价格由高到低':
      filteredImages.value.sort((a,b)=>b.price-a.price);
      break;
    case '价格由低到高':
      filteredImages.value.sort((a,b)=>a.price-b.price);
      break;
  }
  console.dir(filteredImages.value)
  loadedIndex.value = 0;
}

onMounted(() => {
  getGoods();
  locatedAndOpenDialog();
})

watch(ifSortByPrice, (newIfSortByPrice) => {
  if (newIfSortByPrice) {
    applyFilters();
    ifSortByPrice.value = false;
  }
})

watch(input, () => {
  applyFilters();
})

watch(route, (newRoute) => {
  goodsID.value = newRoute.query.goodsID;
  categoryId.value = newRoute.query.categoryId
  applyFilters()
  locatedAndOpenDialog();
})

watch(allImages, () => {
  applyFilters();
})

function handleClose(){
  if(goodsID.value){
  dialogVisible.value = false
  router.push("/store")
  }
  else{
    dialogVisible.value=false
  }
}
</script>

<style lang="scss" scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.page-container {
  height: 100vh;
  overflow-y: auto;
}

.infinite-list {
  padding: 0;
  list-style: none;
}
.infinite-list::-webkit-scrollbar {
  display: none;
}

.infinite-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px;
  margin-left: 15%;
  margin-right: 15%;
  margin-top: 2%;
  background: rgb(244 244 244);
  color: #e0e0e058;
}
.infinite-list-item:first-child {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px;
  margin-top: 0%;
  margin-left: 15%;
  margin-right: 15%;
  background: rgb(244 244 244);
  color: #e0e0e058;
}

.image-container {
  width: 20%;
  align-items: center;
  justify-content: center;
  margin-right:25px;
  background-color: #ffffff;  
}
.infinite-list-item .image-container:last-child {
  margin-right: 0;
}
.image-container:hover {
  box-shadow: 0 4px 8px rgba(255, 0, 0, 0.1);
  /* 无需在此处为hover状态本身设置transition，因为它不是属性的变化 */
}

.image-container:hover .productImg {
  opacity: 0.8;
}

.image-container:hover .product-image-text {
  color: #000; /* 文本颜色 */
  font-weight: 800;
  /* 如果需要改变字体大小，取消以下行的注释 */
  /* font-size: 12px; */
}

.image {
  width: 100%;
  height: auto;
  
}

//商品详情页面
.productImage{
  width: 600px;
  box-shadow: inset;
  border-radius: 4%;
  margin-left: 4%;
  margin-right: 5%;
}
.productName{
  height: auto;
// background-color: aquamarine;
}
.productText{
  margin-top: 2%;
  height: auto;
}
.productPrice{
  height: 80px;
  background-color:#fff5f5;
  display: flex;
  align-items: center;
  margin-top: 5%;
}
.productCart{
  height:"200px"; 
  overflow:"none";
}

.PnText{
  font-size: 20px;
  font-weight: 1000;
}
.PtText{
  font-size: 14px;
}
.PpText{
  
  font-size: 30px;
  color: #ff3e3e;
}
.TtText{
  font-size: 20px;
  color: #ff3e3e;
}


// 弹窗内容
.popover-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1000px;
  height: 500px;
} 

.popover-image {
  width: 100%;
  height: 98%;
  align-items: center
}

//输入框样式
.input {
    height: 36px;
    width: 75%;
    border-radius: 4px;
  }
  
//排序 搜索事件
.active_product{
  height: 70px;
  display: flex;
  align-items: center; 
  justify-content: flex-start;
  padding: 0 12%;
}
.flex-item {
 
  max-height: 100%; 
  margin-right: 10px
}
::v-deep .el-popover{
  min-width:500px;
}

.search{
    width: 20%;
    margin-left: 10px;
}
</style>